package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.ChannelVideoDAO;
import com.group4.DAO.UserDAO;
import com.group4.DAO.VideoDAO;
import com.group4.DB.ChannelVideo;
import com.group4.DB.User;
import com.group4.DB.Video;

@WebServlet( name="AddChannelVideo", displayName="AddChannelVideo", urlPatterns = {"/addChannelVideo"})
public class AddChannelVideo extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5819366367895397005L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Get the printwriter object from response to write the required json
		// object to the output stream
		
		
		String videoId = request.getParameter("video_id");
		String channelId = request.getParameter("channel_id");
		String userName = request.getParameter("username");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		
		if(videoId==null || channelId == null || userName == null ){
			jsonObject.addProperty("error", "missing parameter!");
			out.print(jsonObject);
			out.flush();
		}else {
			UserDAO user = User.getUserWithUsername(userName);
			if( user != null ){
				VideoDAO video = Video.getVideoWithID(Integer.valueOf(videoId));
				if(video != null ){
					int channelInt = Integer.valueOf(channelId);
					int videoInt = Integer.valueOf(videoId);
					ChannelVideoDAO channelVideo = new ChannelVideoDAO(channelInt, videoInt);
					boolean res = ChannelVideo.addChannelVideo(channelVideo);
					if(res){
						Gson gson = new Gson();
			            String json = gson.toJson(channelVideo);
			            out.print(json);
						out.flush();
					} else {
						jsonObject.addProperty("error", "Error occured while adding channel video!");
						out.print(jsonObject);
						out.flush();
					}
				 } else{
					jsonObject.addProperty("error", "No such video");
					out.print(jsonObject);
					out.flush();
				}
				
			}
			else{
				jsonObject.addProperty("error", "No such user");
				out.print(jsonObject);
				out.flush();
			}
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
				
	}

}
